import { observable, action, computed } from 'mobx'

class AppleStore {
  @observable 
  pickableList = [
    {
      id: 0,
      weight: 215,
      isEaten: false,
    },
    {
      id: 1,
      weight: 203,
      isEaten: false,
    }
  ]
  
  buttonText = '摘苹果'

  isPicking = false

  currentId = 2

  @computed get current() {
    let current = {
      appleNow: {
        weight: 0,
        count: 0
      },
      appleEaten: {
        weight: 0,
        count: 0
      }
    }
    this.pickableList.forEach(apple => {
      let selector = apple.isEaten ? 'appleEaten':'appleNow';
      current[selector].count ++;
      current[selector].weight += apple.weight;
    })
    return current
  }

  @action.bound eatApple(appleId) {
    this.pickableList.forEach((apple, index) => {
      if(apple.id === appleId){
        this.pickableList[index].isEaten = true
        this.pickableList[index].count ++
      }
    })
  }

  @action.bound pickApple() {
    if(this.isPicking) return
    this.isPicking = true
    this.buttonText = '正在采摘...'
    Promise.resolve().then(res => {
      let weight = Math.floor(200 + Math.random() * 50);
      this.isPicking = false
      this.buttonText = '摘苹果'
      this.pickableList.push({
        id: this.currentId ++,
        weight,
        isEaten: false
      })
    })
  }
}

const appStore = new AppleStore()

export default appStore
